package com.whlilong.jxc.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Properties;

import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.MessageDialog;

import ET99jni.CET99;
import ET99jni.ET99Def;
import ET99jni.IET99;
import ET99jni.RTException;

public class FileUtil {

	private static String curMonths;
	private static String curDays;
	private static String curYear;
	private static String str1;
	private static String str2;
	private static String str3;
	private static String str4;
	private static String str5;
	private static String str6;
	private static String mds;
	private static String dms;

	public static String getWorkspace() {

		String s = new File(".").getAbsolutePath();
		// String s = Platform.getInstanceLocation().getURL().toString();
		// s = s.substring(s.indexOf("/")+1);
		s = s.substring(0, s.length() - 1);

		s = s.replace("\\", "/");
		return s;
	}
	/**
	 * 锟斤拷��拷锟斤拷锟斤拷锟斤拷锟斤拷锟借�Register.txt锟斤拷娆㈡�锟斤拷
	 * 
	 * @param filePathAndName
	 * 				��拷锟界�锟斤拷缂�拷锟界�锟斤拷锟斤拷锟芥�璺猴拷
	 * @param content
	 * 				濞��锟斤拷锟斤拷�癸拷
	 * 
	 */
	public static void writeTxt(String filePathAndName, String content){
		  String s = new String();
		  try {
			  if(filePathAndName.equals("")||filePathAndName==null)
				  return;
		   File f = new File(filePathAndName+"Register.txt");
		   BufferedWriter output = new BufferedWriter(new FileWriter(f));
		   if(f.exists()){
		    System.out.print("文件存在");
		    output.write(content);
		   }else{
		    System.out.print("文件不存在");
		    return;
//		    f.createNewFile();//娑�拷锟斤拷�ワ拷锟斤拷缂�
//		    output.write(content);
		   }
		   output.close();
		  } catch (Exception e) {
		   e.printStackTrace();
		  }
		
	}

	/**
	 * ���锟斤拷锟斤拷锟斤拷娆�拷锟斤拷
	 * 
	 * @param filePathAndName
	 *            ��拷锟界�锟斤拷缂�拷锟界�锟斤拷锟斤拷锟芥�璺猴拷
	 * @param encoding
	 *            锟斤拷锟斤拷锟芥�锟斤拷锟斤拷锟斤拷锟斤拷锟藉�锟�	 * @return �╋拷锟斤拷锟斤拷锟斤拷娆�拷锟斤拷�癸拷
	 */
	public static String readTxt(String filePathAndName, String encoding) {
		encoding = encoding.trim();
		StringBuffer str = new StringBuffer("");
		String st = "";
		try {
			FileInputStream fs = new FileInputStream(filePathAndName);
			InputStreamReader isr;
			if (encoding.equals("")) {
				isr = new InputStreamReader(fs);
			} else {
				isr = new InputStreamReader(fs, encoding);
			}
			BufferedReader br = new BufferedReader(isr);
			String data = "";
			while ((data = br.readLine()) != null) {
				str.append(data + " ");
			}
			st = str.toString();
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			st="";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return st;

	}
	
	/**
	 * ���锟斤拷锟斤拷�猴拷锟�
	 */
	public static String getDogPath(){
		String dogPath = "";
		File[] roots = File.listRoots();   
	    FileSystemView fSysView = FileSystemView.getFileSystemView();   
	  
	    for (int i = 0; i < roots.length; i++) { 
	    	String type = fSysView.getSystemDisplayName(roots[i]);
	    	String[] name = type.split(" ");
	     if(name[0].equals("REGISTER")){
	    	 String url = roots[i].toURI().toString();
	    	 dogPath = url.substring(url.indexOf("/")+1);
	     }
	    }
		return dogPath;
	}

	/**
	 * 锟斤拷锟藉��ワ拷锟斤拷
	 */
	public static String generateRegist() {
		try {
			Process process = Runtime.getRuntime().exec("ipconfig /all");
			InputStreamReader ir = new InputStreamReader(process
					.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			String line;
			Properties props = System.getProperties(); //
			curYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
			int curMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
			if (curMonth > 9)
				curMonths = curMonth + "";
			if (curMonth < 10 && curMonth >= 0) {
				curMonths = "0" + curMonth;
			}
			int curDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
			int md = curMonth + curDay;
			if (md > 9)
				mds = md + "";
			if (md < 10 && md >= 0) {
				mds = "0" + md;
			}
			int dm = Math.abs(curMonth - curDay);
			if (dm > 9)
				dms = dm + "";
			if (dm < 10 && dm >= 0) {
				dms = "0" + dm;
			}

			if (curDay > 9)
				curDays = curDay + "";
			if (curDay < 10 && curDay >= 0) {
				curDays = "0" + curDay;
			}
			while ((line = input.readLine()) != null) {
				if (props.getProperty("os.name").equals("Windows Vista")) {
					if (line.indexOf("�����ַ")> 0){
						String MACAddr = line.substring(line.indexOf("-") - 2);

						String[] str = MACAddr.split("-");
						str1 = str[0] + curYear.substring(2, 4);
						str2 = str[1] + curYear.subSequence(0, 2);
						str3 = str[2] + curMonths;
						str4 = str[3] + curDays;
						str5 = str[4] + mds;
						str6 = str[5] + dms;
						return str1 + "-" + str2 + "-" + str3 + "-" + str4
								+ "-" + str5 + "-" + str6;
					}

				} else {
					if (line.indexOf("Physical Address") > 0) {
						String MACAddr = line.substring(line.indexOf("-") - 2);

						String[] str = MACAddr.split("-");
						str1 = str[0] + curYear.substring(2, 4);
						str2 = str[1] + curYear.subSequence(0, 2);
						str3 = str[2] + curMonths;
						str4 = str[3] + curDays;
						str5 = str[4] + mds;
						str6 = str[5] + dms;
						return str1 + "-" + str2 + "-" + str3 + "-" + str4
								+ "-" + str5 + "-" + str6;
					}
				}

			}
		} catch (java.io.IOException e) {
			System.err.println("IOException " + e.getMessage());
		}
		return "";
	}
	
	/**
	 * 读取狗中的注册信息
	 * @param code 
	 * @return
	 */
	public static String readRegistcode(String rcode) {
		IET99 ET99 = new CET99();
		ET99Def flag = new ET99Def();
		String code = "";
		String chpid = "ffc5eb78";
		String chpin = "ffffffffffffffff";
		byte[] tText = new byte[64];
		int[] tokenCount = new int[1];
		char[] charPid = new char[8];
		char[] charpin = new char[16];
		char[] charPin = new char[rcode.length()];
		byte[] pid = new byte[8];
		byte[] userPin = new byte[16];
		byte[] rc = new byte[rcode.length()];
		for(int i=0;i<8;i++)
		{
			charPid[i] = chpid.charAt(i);
			pid[i] = (byte)charPid[i];
		}
		for(int j=0;j<16;j++)
		{
			charpin[j] = chpin.charAt(j);
			userPin[j] = (byte)charpin[j];
		}
		for(int j=0;j<rcode.length();j++)
		{
			charPin[j] = rcode.charAt(j);
			rc[j] = (byte)charPin[j];
		}
		try
		{
			System.out.println("Try to Find ET99...");
			ET99.FindToken(pid,tokenCount);
			if (tokenCount[0]!=0)
				System.out.println("Find ET99!");
			System.out.println("Try to open a token...");
			ET99.OpenToken(pid,1);
			System.out.println("Open a ET99 success!");
			System.out.println("Verify user pin...");
			ET99.Verify(0,userPin);
			System.out.println("Verify user pin success!");   
//			System.out.println("Write ET99...");  
//            ET99.Write(0, rcode.length(), rc);
			System.out.println("Read ET99...");     
	        ET99.Read(0, rcode.length(), tText);
	        code = new String(tText);
	        code = code.substring(0,rcode.length());
		}
		catch(RTException e)
		{
			System.out.println(e.HResult()+":"+e.getMessage());
			ET99.CloseToken();
			return "";
		}
		return code;
	}
}
